#!/bin/bash

# 设置脚本在发生错误时停止执行
set -e

# 输出日志函数
log() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - INFO - $1"
}

# 错误处理函数
error() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - ERROR - $1"
    exit 1
}

# 初始化 Kubernetes 集群
log "Initializing Kubernetes cluster..."
sudo kubeadm init \
--image-repository registry.aliyuncs.com/google_containers \
--kubernetes-version v1.27.4 \
--pod-network-cidr=10.10.20.0/24 \
--cri-socket unix:///var/run/cri-dockerd.sock
if [ $? -ne 0 ]; then
    error "Failed to initialize Kubernetes cluster."
fi
log "Kubernetes cluster initialized successfully."

log "All tasks completed successfully."

# 创建 .kube 目录
log "Creating .kube directory..."
mkdir -p $HOME/.kube
if [ $? -ne 0 ]; then
    error "Failed to create .kube directory."
fi
log ".kube directory created successfully."

# 复制 admin.conf 文件到 .kube/config
log "Copying admin.conf to .kube/config..."
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
if [ $? -ne 0 ]; then
    error "Failed to copy admin.conf to .kube/config."
fi
log "admin.conf copied to .kube/config successfully."

# 修改 .kube/config 文件的所有权
log "Changing ownership of .kube/config..."
sudo chown $(id -u):$(id -g) $HOME/.kube/config
if [ $? -ne 0 ]; then
    error "Failed to change ownership of .kube/config."
fi
log "Ownership of .kube/config changed successfully."

log "All tasks completed successfully."